import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController,
  Events,
  LoadingController,
  App
} from "ionic-angular";
import { TeamSeriveProvider } from "../../../providers/team-serive/team-serive";
import { BaseUI } from "../../../common/baseUI";
/**
 * Generated class for the TdPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: "page-team",
  templateUrl: "team.html"
})
export class TdPage extends BaseUI {
  teamDatas: Array<any> = [];
  path: string;
  //是否有权限创建团队 没请求接口确认是否有权限前为空 减少二次请求
  canCreate;
  //加载提示框
  loading;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public teamSeriveProvider: TeamSeriveProvider,
    public toastCtrl: ToastController,
    public events: Events,
    public loadingCtrl: LoadingController,
    public app: App
  ) {
    super();
    //订阅团队创建事件
    
    events.subscribe("team:created", () => {
      this.init();
    });
    
  }

  ionViewWillEnter() {
    // if (this.teamDatas.length != 0) return;
    //进入时显示正在加载
    this.loading = this.showLoading(this.loadingCtrl, "加载中");
    this.init();
    
  }

  init() {
    this.getTeamAll();
  }

  //获取全部团队
  getTeamAll() {
    this.teamSeriveProvider.getTeamAll().subscribe(
      data => {
        this.loading.dismiss();
        if (data != null) {
          if (data.status != 500) {
            this.teamDatas = data;
            return;
          } else {
            this.loginTimeOut();
          }
        }
      },
      err => {
        super.showToast(this.toastCtrl, "请检查网络连接之后重试");
      }
    );
  }

  //跳转到团队详情界面
  openTeamDetail(teamcode) {
    this.navCtrl.push("TeamDetailsPage", {
      teamcode
    });
  }

  //我的团队界面
  openMyTeamPage() {
    this.navCtrl.push("TeamMyPage");
  }

  //新建团队界面
  openNewTeamPage() {
    //目前所有人都可以创建团队
    this.navCtrl.push("TeamNewPage");

    //判断是否有创建团队的权限 只请求一次
    // if (this.canCreate == null) {
    //   this.teamSeriveProvider.getCanCreate().subscribe(
    //     data => {
    //       if (data.status == 200) {
    //         this.navCtrl.push("TeamNewPage");
    //         this.canCreate = true;
    //       } else if (data.status == 500) {
    //         this.loginTimeOut();
    //       } else {
    //         this.canCreate = false;
    //         super.showToast(this.toastCtrl, "没有新建团队的权限");
    //       }
    //     },
    //     err => {
    //       super.showToast(this.toastCtrl, "请检查网络连接之后重试");
    //     }
    //   );
    //   return;
    // }
    // if (this.canCreate) this.navCtrl.push("TeamNewPage");
    // else super.showToast(this.toastCtrl, "没有新建团队的权限");
  }

  //token失效
  loginTimeOut() {
    super.showToast(this.toastCtrl, "登录失效，请重新登录");
    this.app.getRootNav().setRoot("LoginOrRegisterPage");
  }
}
